package org.jackysoft.service.impl;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.jackysoft.entity.NewsConfig;
import org.jackysoft.entity.nosql.NewsCatalog;
import org.jackysoft.entity.nosql.Province;
import org.jackysoft.service.AbstractNoSqlServiceImpl;
import org.jackysoft.service.NewsCatalogService;
import org.jackysoft.service.NewsConfigService;
import org.jackysoft.service.NewsInfoService;
import org.jackysoft.service.ProvinceService;
import org.jackysoft.util.HttpUtil;
import org.jackysoft.util.Page;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Service;

@Service
public class ProvinceServiceImpl extends
		AbstractNoSqlServiceImpl<Province> implements ProvinceService {

	/**
	 * 
	 */
	private static final long serialVersionUID = 2435290401297502340L;
	private NewsCatalogService cataService;
	private NewsInfoService infoService;
	private NewsConfigService newscfgService;

	
	
	public ProvinceServiceImpl() {
		super(Province.class);
		
	}

	@Override
	public Province get(int page, int rows, String name, String firstChildId)
			throws DataAccessException {
		Province bean = new Province();
		String cid = cataService.tops(name);
		if (StringUtils.isBlank(cid)) {
			// 没有开通
			bean.setOpened(false);
			return bean;
		}
		String childId = firstChildId;
		if (StringUtils.isBlank(childId)) {
			NewsConfig nc = newscfgService.get(cid);
			if (nc != null)
				childId = nc.getDefaultFirstSid();
		}
		
		if(StringUtils.isBlank(childId)){
			bean.setOpened(false);
			return bean;
		}
		
		String topMenu = cataService.topMenus(cid, childId);
		NewsCatalog firstNc = cataService.get(childId);

		if (firstNc.isExternal()) {
			// 直接获取外部url内容
			bean.setFromext(true);
			String extContent = HttpUtil.getResponseString(firstNc.getHref());
			bean.setExtContent(extContent);
			return bean;
		}

		Page pageData = new Page();
		pageData.setPage(page);
		pageData.setRecords(infoService.countByCatalog(childId));
		pageData.setOffset(rows);
		pageData.setRows(infoService.gets(page, rows, childId));

		bean.setId(cid);
		bean.setName(name);
		bean.setMenu(topMenu);
		bean.setPageData(pageData);
		return bean;
	}

	@Resource
	public void setCataService(NewsCatalogService cataService) {
		this.cataService = cataService;
	}

	@Resource
	public void setInfoService(NewsInfoService infoService) {
		this.infoService = infoService;
	}

	@Resource
	public void setNewscfgService(NewsConfigService newscfgService) {
		this.newscfgService = newscfgService;
	}

}
